# Copyright (c) 2019 Presto Labs Pte. Ltd.
# Author: xguo

import datetime
import pathlib
import platform

import dateutil.parser
from absl import app, flags

from coin.base.datetime_util import iterate_date
from coin.experimental.xguo.fruit.util.convert_symbol_to_product import convert_symbol_to_product
from coin.experimental.xguo.fruit.util.feed_util import (
    AutoInc,
    load_products_feed_as_json,
    get_moving_average,
    get_moving_diff,
    get_moving_return,
    get_mid_series,
    get_trade_qty_series,
    to_mid_night,
    load_og_log,
    get_submit_price,
    get_fill_price,
    get_fill_qty,
)

#matplotlib.use('Agg')
import matplotlib.pyplot as plt

FLAGS = flags.FLAGS


def plot_result(prices, submit_price, fill_price):
  plt.figure(figsize=(20, 10))
  s1 = datetime.timedelta(seconds=0.5)
  p1 = convert_symbol_to_product('XRP-BTC.Okex')
  p2 = convert_symbol_to_product('XRP-USDT.Okex')
  p3 = convert_symbol_to_product('BTC-USDT.Okex')

  # p4 = prices[p2].asfreq(s1, method='backfill') / prices[p3].asfreq(s1, method='backfill')
  plt.plot(prices[p1].index, prices[p1], label=p1.full_symbol, marker='.')
  # plt.plot(p4.index, p4, label='calc')
  plt.plot(submit_price[0].index, submit_price[0], label='buy', marker='.')
  plt.plot(submit_price[1].index, submit_price[1], label='sell', marker='.')

  plt.plot(fill_price[0].index, fill_price[0], label='fill buy', marker='.')
  plt.plot(fill_price[1].index, fill_price[1], label='fill sell', marker='.')

  plt.legend()
  plt.show()


def main(_):
  if FLAGS.home_dir is None:
    if 'hive' in platform.node():
      home_dir = pathlib.Path('/remote/iosg/home/xguo')
    else:
      home_dir = pathlib.Path.home()
  else:
    home_dir = pathlib.Path(FLAGS.home_dir)

  root_dir = home_dir.joinpath('converted_book')

  products = []
  for symbol in FLAGS.symbol.split(','):
    product = convert_symbol_to_product(symbol)
    products.append(product)

  if '-' in FLAGS.trading_date:
    start_date, end_date = FLAGS.trading_date.split('-')
    start_date = dateutil.parser.parse(start_date)
    end_date = dateutil.parser.parse(end_date)
    trading_dates = list(iterate_date(start_date, end_date))
  else:
    trading_dates = [dateutil.parser.parse(FLAGS.trading_date)]

  feeds = load_products_feed_as_json(root_dir, trading_dates, products)
  prices = {}
  for product, feed_list in feeds.items():
    prices[product] = get_mid_series(feed_list)

  og_log = load_og_log(pathlib.Path.home().joinpath('xunke12.Spot.Okex.20190606.json'))
  submit_price = get_submit_price(og_log)
  fill_price = get_fill_price(og_log)
  fill_qty = get_fill_qty(og_log)
  print(fill_price[0].mean())
  print(fill_price[1].mean())
  print(fill_qty[0].sum())
  print(fill_qty[1].sum())

  plot_result(prices, submit_price, fill_price)


if __name__ == '__main__':
  flags.DEFINE_string(
      'symbol',
      None,
      'Specify product full symbol.',
  )

  flags.DEFINE_string('trading_date', None, 'Trading date.')

  flags.DEFINE_string('home_dir', None, 'Home directory.')
  app.run(main)
